package com.gree.shyun.util;

import com.gree.shyun.bean.UrlSpit;
import com.gree.shyun.bean.VMLayoutBean;
import com.gree.shyun.entity.Form;
import com.gree.shyun.entity.FormPage;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {


    /**
     * 获取url拆分数据
     * @param path
     * @return
     */
    public static UrlSpit getUrlSpit(String path){
        if(path==null){
            return null;
        }
        UrlSpit urlSpit = new UrlSpit();
        boolean hasApi = path.contains("api/");
        String spit = hasApi?"api/":"/";
        boolean hasDomain = path.contains("//");
        if(hasDomain) {
            if (!hasApi) {
                path = path.replaceFirst("//", "&&");
            }
        }
        int index= path.indexOf(spit);
        String domain = "";
        if(hasDomain) {
            domain = path.substring(0, index);
            if(!hasApi) {
                domain = domain.replaceFirst("&&", "//");
            }
        }

        int wh = 0;
        if(path.contains("?")){
            wh=path.indexOf("?");
        }
        String url = wh>0?path.substring(index,wh):path.substring(index);
        String param = null;
        if(wh>0){
            param = path.substring(wh+1);
        }
        urlSpit.setDomain(domain);
        urlSpit.setUrl(url);
        urlSpit.setAlias(getAlias(url));
        if(param!=null) {
            urlSpit.setParam(urlParmToJson(param));
        }
        return urlSpit;
    }

    /**
     * 从url里获取别名
     * @param url
     * @return
     */
    public static String getAlias(String url){
        String result = "";
        if(url.contains("/")){
            String[] u = url.split("/");
            if(u.length>2){
                result =  CommonUtil.firstToUpperCase(u[u.length-2])+CommonUtil.firstToUpperCase(u[u.length-1]);
            }else if(u.length>1){
                result =  CommonUtil.firstToUpperCase(u[0])+CommonUtil.firstToUpperCase(u[u.length-1]);
            }else if(u.length>0){
                result =  CommonUtil.firstToUpperCase(u[0]);
            }
        }
        result = CommonUtil.firstToUpperCase(result);
        if(result.contains(".")){
            result = result.substring(0,result.indexOf("."));
        }
        return result;
    }

    /**
     *  url里的参数转json
     * @param param
     * @return
     */
    public static String urlParmToJson(String param){
        if(param==null){
            return null;
        }
        List<String> arr = new ArrayList<>();
        if(param.contains("&")){
            String[] s = param.split("&");
            arr.addAll(Arrays.asList(s));
            for(int i = 0 ;i<arr.size();i++) {
                String a = arr.get(i);
                if (a.length() < 2 || !a.contains("=")) {
                    arr.remove(i);
                    i--;
                }
            }
        }else{
            arr.add(param);
        }
        String json = "{";
        int i = 0;
        int size = arr.size();
        for(String s:arr){
            s = s.replaceFirst("=","\":\"");
            json+="\""+s+"\"";
            if (i < size - 1) {
                json+=",";
            }
            i++;
        }
        json+="}";
        return json;
    }

    /**
     * 获取配置
     * @param path
     * @return
     */
    public static Map<String,String> getConfig(String path){
        Map<String,String> map = new HashMap<>();
        try {
            String file = JsonXmlUtils.fileToString(path);
            String[] ss = file.split("\n");
            for(String s:ss){
                if (s.length() > 2 && s.contains("=")) {
                    String key = s.substring(0,s.indexOf("="));
                    String value = s.substring(s.indexOf("=")+1);
                    map.put(key,value);
                }
            }
            return map;
        } catch (IOException e) {
        }
        return null;
    }

    /**
     *  保存配置
     * @param path
     * @param map
     * @return
     */
    public static boolean saveConfig(String path,Map<String,String> map){
        String file = "";
        for(String key:map.keySet()){
            file+=key+"="+map.get(key)+"\n";
        }
        try {
            JsonXmlUtils.stringToFile(file,path);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 清除换行等
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 获取字符串中间内容
     * @param str
     * @param leftRex
     * @param rightRex
     * @return
     */
    public static String getBetweenStr(String str,String leftRex,String rightRex){
        Pattern p=Pattern.compile(leftRex+"(.*?)"+rightRex);
        Matcher m=p.matcher(str);
        if(m.find()){
            return  m.group(1);
        }
        return null;
    }
    /**
     * 首字母转小写
     * @param str
     * @return
     */
    public static String firstToLowerCase(String str){
        return str.substring(0,1).toLowerCase()+str.substring(1);
    }

    /**
     *  首字母转大写
     * @param str
     * @return
     */
    public static String firstToUpperCase(String str){
        if(str.length()>1){
            return str.substring(0,1).toUpperCase()+str.substring(1);
        }
        return str.toUpperCase();
    }

    /**
     *  获取中文首字母拼音
     * @param str
     * @return
     */
    public static String getFirstPinyin(String str){
        if(str==null){
            return "";
        }
        char[] charArray = str.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        // 设置大小写格式
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 设置声调格式：
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < charArray.length; i++) {
            if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
                String[] hanyuPinyinStringArray = new String[0];
                try {
                    hanyuPinyinStringArray = PinyinHelper
                            .toHanyuPinyinStringArray(charArray[i], defaultFormat);
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                }
                if (hanyuPinyinStringArray != null) {
                    pinyin.append(hanyuPinyinStringArray[0].charAt(0));
                }
            }else{
                pinyin.append(charArray[i]);
            }
        }
        return pinyin.toString();
    }

    /**
     *  重复id处理
     * @param formPages
     * @param id
     * @return
     */
    public static String getPageLastId(List<FormPage> formPages,String id){
        for(FormPage formPage:formPages){
            if(id.equals(formPage.getPage_id())){
                String index=formPage.getPage_id().replaceAll(".*[^\\d](?=(\\d+))","");
                try {
                    int in = Integer.parseInt(index);
                    return id+(in+1);
                }catch (Exception e){
                    return id+1;
                }
            }
        }
        return id;
    }

    /**
     * 重复id处理
     * @param forms
     * @param id
     * @return
     */
    public static String getFormLastId(List<Form> forms, String id){
        for(Form form:forms){
            if(id.equals(form.getId())){
                String index = form.getId().replaceAll(".*[^\\d](?=(\\d+))","");
                try {
                    int in = Integer.parseInt(index);
                    return id+(in+1);
                }catch (Exception e){
                    return id+1;
                }
            }
        }
        return id;
    }

    /**
     * 获取中间内容
     * @param text
     * @param left
     * @param right
     * @return
     */
    public static List<String> getMiddle(String text,String left,String right){
        Pattern p=Pattern.compile("("+left+"(.+)"+right+")");
        Matcher m=p.matcher(text);
        List<String> list = new ArrayList<>();
        while(m.find()) {
            String trigger=m.group(0);
            trigger = trigger.replaceAll(left,"");
            trigger = trigger.replaceAll(right,"");
            list.add(trigger);
        }
        return list;
    }
    public static String getMiddleStr(String text,String left,String right){
        List<String> list = getMiddle(text,left,right);
        if(list.size()>0){
            return list.get(0);
        }
        return "";
    }



    /**
     * 替换java代码里的整个词
     * @param text
     * @param val
     * @param replaceVal
     * @return
     */
    public static String replaceWord(String text,String val,String replaceVal){
        if(!text.contains(val)){
            return text;
        }
        String line = text.replaceAll(" ","");
        int lineIndex = line.indexOf(val);
        boolean leftHasChar = true;
        boolean rightHasChar = true;
        if(lineIndex==0){
            leftHasChar = false;
        }else{
            char leftChar =line.charAt(lineIndex-1);
            switch (leftChar){
                case 40:
                case 61:
                    leftHasChar = false;
                    break;
            }
        }
        if(line.length()==lineIndex+val.length()){
            rightHasChar = false;
        }else{
            char rightChar =line.charAt(lineIndex+val.length());
            switch (rightChar){
                case 46:
                case 41:
                case 61:
                    rightHasChar = false;
                    break;
            }
        }
        if(!leftHasChar&&!rightHasChar){
            text = text.replaceAll(val,replaceVal);
        }
        return text;
    }


    public static  String replaceXsf(String trline){
        if(trline.startsWith("public")
                ||trline.startsWith("private")
                ||trline.startsWith("protected")){
            trline = trline.replaceAll("public","");
            trline = trline.replaceAll("private","");
            trline = trline.replaceAll("protected","");
            trline = trline.trim();
        }
        return trline;
    }

    public static boolean  isStartXsf(String trline){
        if(trline.startsWith("public")
                ||trline.startsWith("private")
                ||trline.startsWith("protected")){
            return true;
        }
        return false;
    }

    public static boolean endWIdth(String text,String...fix){
        for(String f:fix){
            if(text.endsWith(f)){
                return true;
            }
        }
        return false;
    }
    public static VMLayoutBean findByName(List<VMLayoutBean> list, String name){
        for(VMLayoutBean v:list){
            if(v.getLayoutName().contains(name)){
                return v;
            }
        }
        return null;
    }

    public static boolean isIn(Set<String> index,String value){
        for(String in:index){
            if(value.trim().contains(in.trim())){
                return  true;
            }
        }
        return false;
    }


    /**
     *  根据分页大小和总数量 获取总页数
     * @param allCount
     * @param pageSize
     * @return
     */
    public static int getAllPage(int allCount,int pageSize){
        return  (allCount-1)/pageSize+1 ;
    }

    /**
     *  unicode转utf8
     * @param theString
     * @return
     */
    public static String unicodeToUtf8(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }
}
